<template>
  <div class="container">
    <h1 class="title">新增商品</h1>

    <!-- 商品表单 -->
    <div class="form-card">
      <el-form :model="form" label-width="100px" style="max-width: 500px;">
        <el-form-item label="商品名称">
          <el-input v-model="form.productName" placeholder="请输入商品名称" />
        </el-form-item>

        <el-form-item label="商品分类">
          <el-select v-model="form.category" placeholder="请选择商品分类">
            <el-option 
              v-for="item in categories" 
              :key="item.value" 
              :label="item.label" 
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="库存">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>

        <el-form-item label="价格（元）">
          <el-input-number v-model="form.price" :min="0" :step="0.01" />
        </el-form-item>

        <el-form-item label="商品状态">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">上架</el-radio>
            <el-radio :label="0">下架</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="商品图片">
          <div class="image-uploader" @click="triggerFileInput">
            <img v-if="form.image" :src="form.image" alt="preview" class="image-preview" />
            <div v-else class="upload-placeholder">
              <span class="upload-icon">＋</span>
              <p>上传图片</p>
            </div>
            <input ref="fileInput" type="file" accept="image/*" @change="handleImageUpload" hidden />
          </div>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="addProduct">添加商品</el-button>
          <el-button @click="goBack" style="margin-left: 10px;">返回</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { useRouter } from "vue-router";
import { ElMessage } from "element-plus";
import request from "@/utils/request";

const router = useRouter();

// 商品分类选项
const categories = [
  { label: '居家', value: '居家' },
  { label: '美食', value: '美食' },
  { label: '服饰', value: '服饰' },
  { label: '运动', value: '运动' },
  { label: '个护', value: '个护' },
  { label: '严选', value: '严选' },
  { label: '数码', value: '数码' },
  { label: 'car', value: 'car' },
  { label: '杂货', value: '杂货' }
];

const form = reactive({
  productName: "",
  category: "", // 添加分类字段
  stock: 0,
  price: 0,
  status: 1,
  image: null,
  imageFile: null
});

const fileInput = ref(null);

const triggerFileInput = () => {
  fileInput.value && fileInput.value.click();
};

// 处理图片上传
const handleImageUpload = (event) => {
  const file = event.target.files[0];
  if (file) {
    form.imageFile = file;
    form.image = URL.createObjectURL(file);
  }
};

// 添加商品
const addProduct = () => {
  if (!form.productName || !form.price || !form.category) {
    ElMessage.warning("请填写完整信息");
    return;
  }

  // 准备表单数据
  const formData = new FormData();
  
  // 单独添加每个字段，而不是作为JSON对象
  formData.append('productName', form.productName);
  formData.append('category', form.category);
  formData.append('stock', form.stock);
  formData.append('price', form.price);
  formData.append('status', form.status);
  
  // 如果有图片文件，则添加到表单中
  if (form.imageFile) {
    formData.append('imageFile', form.imageFile);
  }

  // 调用后端接口 - 修改请求路径，移除多余的 /api
  request.post('/home/merchant/addProductsWithImages', formData)
    .then(res => {
      // 根据后端返回的数据结构调整判断逻辑
      if (res.success === true && res.code === 200) {
        ElMessage.success('商品添加成功');
        // 返回商品列表页
        router.push('/merchant/products');
      } else {
        ElMessage.error(res.message || '商品添加失败');
      }
    })
    .catch(err => {
      console.error('商品添加失败:', err);
      ElMessage.error('商品添加失败: ' + (err.message || '网络错误'));
    });
};

// 返回上一页
const goBack = () => {
  router.go(-1);
};
</script>

<style scoped>
/* 整体布局 */
.container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: "Microsoft YaHei", Arial, sans-serif;
  color: #333;
}

.title {
  text-align: center;
  font-size: 28px;
  font-weight: 700;
  margin-bottom: 30px;
}

/* 表单样式 */
.form-card {
  background: #fff;
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 40px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.06);
}

/* 上传图片 */
.image-uploader {
  width: 160px;
  height: 160px;
  border: 2px dashed #ccc;
  border-radius: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  overflow: hidden;
  background: #fafafa;
  transition: border-color 0.3s;
}

.image-uploader:hover {
  border-color: #409eff;
}

.image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.upload-placeholder {
  text-align: center;
  color: #aaa;
}

.upload-icon {
  font-size: 26px;
  display: block;
  margin-bottom: 6px;
}
</style>